<template>
  <div class="user-avator-dropdown">
    <Dropdown @on-click="handleClick">
      <Tag color="volcano">{{getUserName}}</Tag>
      <Icon :size="18" type="md-arrow-dropdown"></Icon>
      <DropdownMenu slot="list">
        <!-- <DropdownItem name="message">
          消息中心<Badge style="margin-left: 10px" :count="messageUnreadCount"></Badge>
        </DropdownItem> -->
        <DropdownItem name="changePassword">更改密码</DropdownItem>
        <DropdownItem name="logout">退出登录</DropdownItem>
      </DropdownMenu>
    </Dropdown>
    <password-modal @password-valid="handleEdit"></password-modal>
  </div>
</template>

<script>
import './user.less'
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'
import PasswordModal from '../../../password-modal'
export default {
  name: 'User',
  components: {
    PasswordModal
  },
  props: {
    userAvator: {
      type: String,
      default: ''
    },
    messageUnreadCount: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      resp: null,
      postData: null
    }
  },
  computed: {
    ...mapState({
      accountList: state => state.account.accountList
    }),
    ...mapGetters([
      'getUserName'
    ])
  },
  methods: {
    ...mapMutations([
      'setTagNavList'
    ]),
    ...mapActions([
      'handleLogOut',
      'removeCookie',
      'updatePasswordModalState',
      'getAccountList',
      'editAccountData'
    ]),
    logout () {
      this.setTagNavList()
      this.handleLogOut().then(() => {
        this.removeCookie().then(() => {
          this.$router.push({
            name: 'login'
          })
        }).catch(err => {
          console.log(err)
        })
      })
    },
    async changePassword () {
      this.updatePasswordModalState(true)
      const resp = await this.getAccountList({ uname: this.getUserName })
      this.resp = resp
    },
    async handleEdit (playload) {
      this.postData = {
        id: this.resp.data.data.rows[0].id,
        ...playload
      }
      const resp = await this.editAccountData(this.postData)
      if (resp.data.state === '000') {
        this.$Message.success('密码修改成功')
        this.logout()
      } else {
        this.$Message.error('密码修改失败')
      }
      this.updatePasswordModalState(false)
    },
    message () {
      this.$router.push({
        name: 'message_page'
      })
    },
    handleClick (name) {
      switch (name) {
        case 'changePassword': this.changePassword()
          break
        case 'logout': this.logout()
          break
        case 'message': this.message()
          break
      }
    }
  }
}
</script>
